import Funcs from '@/assets/funcs'
const ajaxConfig = {
  isLoading: true, // 是否显示加载条
  isShowMsg: true, // 是否显示成功提示信息
  headers: {
    'x-requested-with': 'XMLHttpRequest',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  }, // 请求Headers
  method: 'GET' // 请求方式
}
const getHttpStatus = function(status) {
  if (!status) {
    return { status: status, msg: '未知异常' }
  }
  if (status < 200) {
    return { status: status, msg: '请求过于频繁，请稍后重试' }
  }
  if (status < 300) {
    return { status: 200, msg: '请求成功' }
  }
  if (status < 400) {
    return { status: status, msg: '请求的资源不存在或无权访问' }
  }
  if (status < 500) {
    return { status: status, msg: '无权访问此资源' }
  }
  return { status: status, msg: '服务器正在打盹，请稍后重试' }
}
/**
 * 注册Vue公共方法、函数
 *
 * @type {{install: quevo.install}}
 */
const Quevo = {
  install: function(Vue, options) {
    Vue.prototype.funcs = Funcs
    // 弹出框
    Vue.prototype.quevoAlert = function(opts) {
      return this.$alert(
        opts.message ? opts.message : '',
        opts.title ? opts.title : '提示',
        {
          confirmButtonText: opts.confirmButtonText
            ? opts.confirmButtonText
            : '确定',
          dangerouslyUseHTMLString: opts.dangerouslyUseHTMLString
            ? opts.dangerouslyUseHTMLString
            : true,
          callback: opts.callback
        }
      )
    }
    // 确认框
    Vue.prototype.quevoConfirm = function(opts) {
      return this.$confirm(
        opts.message ? opts.message : '',
        opts.title ? opts.title : '提示',
        {
          confirmButtonText: opts.confirmButtonText
            ? opts.confirmButtonText
            : '确定',
          cancelButtonText: opts.cancelButtonText
            ? opts.cancelButtonText
            : '取消',
          dangerouslyUseHTMLString: opts.dangerouslyUseHTMLString
            ? opts.dangerouslyUseHTMLString
            : true,
          type: 'warning'
        }
      )
    }
    // 信息窗口
    Vue.prototype.quevoMsgDialog = function(opts) {
      opts.title = opts.title || '消息'
      opts.message = opts.message || ''
      opts.dangerouslyUseHTMLString = opts.dangerouslyUseHTMLString
        ? opts.dangerouslyUseHTMLString
        : true
      opts.confirmButtonText = opts.confirmButtonText
        ? opts.confirmButtonText
        : '确定'
      opts.cancelButtonText = opts.cancelButtonText
        ? opts.cancelButtonText
        : '取消'
      opts.showCancelButton = opts.showCancelButton
        ? opts.showCancelButton
        : true
      return this.$msgbox(opts)
    }
    // 成功提示
    Vue.prototype.quevoSuccess = function(message, duration) {
      return this.$message({
        message: message || '操作成功',
        type: 'success',
        duration: duration || 2000
      })
    }
    // 警告
    Vue.prototype.quevoWarning = function(message, duration) {
      return this.$message({
        message: message || '警告',
        type: 'warning',
        duration: duration || 2000
      })
    }
    // 消息
    Vue.prototype.quevoInfo = function(message, duration) {
      return this.$message({
        message: message || '提示',
        duration: duration || 2000
      })
    }
    // 错误
    Vue.prototype.quevoError = function(message, duration) {
      return this.$message.error({
        message: message || '错误',
        type: 'error',
        duration: duration || 2000
      })
    }
    // AJAX请求
    Vue.prototype.quevoAjax = function(options) {
      const opts = Object.assign({}, ajaxConfig, options)
      let loading
      if (opts.loading) {
        loading = this.$loading({
          lock: true,
          text: opts.loadingText ? opts.loadingText : '',
          spinner: opts.spinner ? opts.spinner : '',
          background: 'rgba(0, 0, 0, 0.7)'
        })
      }
      if (opts.headers) {
        opts.headers['x-requested-with'] = 'XMLHttpRequest'
      } else {
        opts.headers = {
          'x-requested-with': 'XMLHttpRequest',
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
      }
      const http = this.$axios(opts)
      http.then(response => {
        loading && loading.close()
        let result = getHttpStatus(response.status)
        // 验证服务器相应状态码(HttpStatus)
        if (result.status !== 200) {
          opts.isShowMsg && this.quevoWarning(result.msg)
          opts.catch && opts.catch(result)
          return
        }
        result = response.data
        // 验证请求结果(ResultEntity)
        if (!result || !result.status) {
          result = { status: 1100, msg: '请求无响应，无返回内容' }
          opts.isShowMsg && this.quevoWarning(result.msg)
          opts.catch && opts.catch(result)
          return
        }
        // 判断是否有登录
        if (result.status === 5001) {
          this.quevoWarning('尚未登录，请登录后操作', 1200)
          setTimeout(() => {
            location.href = '/login'
          }, 1200)
          return
        }
        // 判断是否请求错误
        if (result.status !== 200) {
          opts.isShowMsg && this.quevoWarning(result.msg)
          opts.catch && opts.catch(result)
          return
        }
        // opts.isShowMsg && this.quevoSuccess(result.msg)
        opts.callback && opts.callback(result)
      })
      return http
    }
    // restful PUT
    Vue.prototype.ajaxPut = function(options) {
      Object.assign(options, { method: 'PUT' })
      this.quevoAjax(options)
    }
    // restful DELETE
    Vue.prototype.ajaxDelete = function(options) {
      Object.assign(options, { method: 'DELETE' })
      this.quevoAjax(options)
    }
    // restful POST
    Vue.prototype.ajaxPost = function(options) {
      Object.assign(options, { method: 'POST' })
      this.quevoAjax(options)
    }
    // restful GET
    Vue.prototype.ajaxGet = function(options) {
      Object.assign(options, { method: 'GET' })
      this.quevoAjax(options)
    }
    // 设置本地缓存
    Vue.prototype.setLocalData = function(key, val, storeName) {
      if (!process.client) {
        return
      }
      if (Funcs.isNull(val)) {
        window.localStorage.removeItem(key)
        if (storeName) {
          this.$store.commit(storeName, null)
        }
        return
      }
      if (Array.isArray(val) || typeof val === 'object') {
        window.localStorage.setItem(key, JSON.stringify(val))
      } else {
        window.localStorage.setItem(key, val)
      }
      if (storeName) {
        this.$store.commit(storeName, val)
      }
    }
    // 移除本地缓存
    Vue.prototype.removeLocalData = function(key, storeName) {
      if (!process.client) {
        return
      }
      window.localStorage.removeItem(key)
      if (storeName) {
        this.$store.commit(storeName, null)
      }
    }
    // 获取本地缓存
    Vue.prototype.getLocalData = function(key, isJson) {
      if (!process.client) {
        return
      }
      const val = window.localStorage.getItem(key)
      if (Funcs.isNull(val)) {
        return val
      }
      return isJson ? JSON.parse(val) : val
    }
    // 清空本地缓存
    Vue.prototype.cleanLocalData = function() {
      if (!process.client) {
        return
      }
      window.localStorage.clear()
    }
  }
}
export default Quevo
